var form;
var $;
var table;
var productType;
var layer;
var upload;
layui.use(['form','jquery','table','layer','upload'],function() {
    form = layui.form;
    $ = layui.jquery;
    table = layui.table;
    layer = layui.layer;
    upload = layui.upload;
    //获取选择的商品类型
    form.on('select(filter)', function(data){
        productType = data.value
    });
    //上架下架状态
    form.on('switch(swi)', function(data){
        var state;
        if(data.elem.checked){
            state = 1;
        }else{
            state = 2;
        }
        $.ajax({
            url:'/Product/updateState',
            data:{"state":state,"id":data.elem.value},
            dataType:'json',
            success:function (data) {
                if(data.data){
                    if(state === 1){
                        layer.msg("上架成功")
                    }else{
                        layer.msg("下架成功");
                    }
                }else{
                    layer.msg("修改失败");
                }

            }
        });
    });

});
var user = JSON.parse(localStorage.getItem('user'));
startTab();
function startTab() {
    $.ajax({
        url:'/Product/queryProduct',
        dataType:'json',
        success:function (data) {
            var arr = [];
            for (var i = 0; i<data.data.length;i++){
                if(data.data[i].result != 2){
                    arr.push(data.data[i]);
                }
            }
            tab(arr);
        }
    });
}

function tab(data){
    table.render({
        elem: '#demo' ,
        data:data,
        toolbar:'#toolutil',
        page:true,
        limit:4,
        cols:[[
            {checkbox:true},
            {field:'productCode',title:'商品编号',align:'center',height:'20px'},
            {title:'商品图片',align:'center',templet:function(data){
                    return "<img src='"+data.mainImage+"'width='80px' height='80px'/>";
                }},
            {field:'productName',title:'商品名称',align:'center'},
            {field:'currentpriceProduct',title:'商品价格',align:'center'},
            {title:'上架/下架',align:'center',templet:function(data){
                    if(data.productSate === 1){
                        return"<input type='checkbox' value='"+data.productId+"' lay-filter='swi' lay-skin='switch' lay-text='上架|下架' checked>";
                    }else if(data.productSate === 0){
                        return "<span>已删除</span>";
                    }else{
                        return"<input type='checkbox' value='"+data.productId+"' lay-filter='swi' lay-skin='switch' lay-text='上架|下架'>";
                    }
                }},
            {field:'categroyTitle',title:'商品分类',align:'center'},
            {field:'productLabel',title:'商品标签',align:'center'},
            {field:'title',title:'审核状态',align:'center',templet:function(data){
                    var result;
                    if(data.result == 1){
                        result = "审核通过";
                    }else if(data.result == 2){
                        result = "待审核";
                    }else{
                        result = "审核驳回";
                    }
                    return "<div>"+result+"</div>" +
                        "<a class='operation' onclick='auditDetails("+data.productId+")'>审核详情</a>";
                }},
            {field:'title',title:'操作',align:'center',templet:function(data){
                    return "<a class='operation' onclick='details("+data.productId+")'>查看</a>  <a class='operation' onclick='edit("+data.productId+")'>编辑</a> <br/>"+
                        "<a class='operation' onclick='commodityLog("+data.productId+")'>日志</a>  <a onclick='delProduct(\""+data.productId+"\",\""+data.productCode+"\")' class='operation'>删除</a>";
                }},
        ]]
    });
}

//查询商品分类数据
startTree();
function startTree() {
    $.ajax({
        url:'/Product/productClass',
        dataType:'json',
        success:function (data) {
            zTree(data.data);
        }
    });
}

var node;
function zTree(data){

    var settingss = {
        view:{
            showIcon:false,
            selectedMulti:false,
        },
        /*edit: {
            enable: true,
            editNameSelectAll:true,
        },*/
        showLine: true,
        root: {
            isRoot: true,
            nodes: []
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "categroyId",  //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check:{
            enable:true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
            chkboxType: { "Y": "p", "N": "s" },
            nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback : { //回调函数
            beforeCheck : function(treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.checkAllNodes(false);
                return true;
            },
            onRightClick : OnRightClick,   //右键事件
            onClick : chooseNode
        }
    };

    function chooseNode(event,treeId ,treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var node = nodes[0];
        if(!node.isParent){
            $.ajax({
                url:'/Product/queryProduct',
                dataType:'json',
                data:{"categoryId":treeNode.categroyId},
                success:function (data) {
                    var arr = [];
                    for (var i = 0; i<data.data.length;i++){
                        if(data.data[i].result != 2){
                            arr.push(data.data[i]);
                        }
                    }
                    tab(arr);
                }
            });
        }
    }


    function OnRightClick(event, treeId, treeNode) {
        node = treeNode;
        if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            zTree.cancelSelectedNode();
            showRMenu("root", event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            categroyId = treeNode.categroyId;

            //zTree.selectNode(treeNode);
            showRMenu(event.target,"node", event.clientX, event.clientY);
        }
    }
    //显示右键菜单
    function showRMenu(event,type, x, y) {
        $("#rMenu").show();
        $("#rMenu").css({"top": y + "px", "left": x + "px", "visibility": "visible"}); //设置右键菜单的位置、可见
        $("body").bind("mousedown", onBodyMouseDown);
    }

//隐藏右键菜单
    function hideRMenu() {
        $("#rMenu").css({"visibility": "hidden"}); //设置右键菜单不可见
        $("body").unbind("mousedown", onBodyMouseDown);
    }
//鼠标按下事件
    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            // $("#rMenu").hide();
            $("#rMenu").css({ "visibility": "hidden"});
        }
        hideRMenu();
    }

    var newCount = 1;
    zTreeObj = $.fn.zTree.init($("#treeDemo"), settingss, data );
    zTreeObj.expandAll(true);
}
//删除分类
function delnode() {
    if(node.categroyId === 1){
        layer.msg("该目录不可删除");
        return;
    }
    if(confirm("确认删除"+node.title+"商品类?")){
        if(node.isParent){
            layer.msg("该目录下面还有子目录，请从最底层目录开始删除!");
            return false;
        }
        $.ajax({
            url:'/Product/delProductCaegory',
            data:{"categoryId":node.categroyId},
            dataType:'json',
            success:function (data) {
                if(data.data){
                    layer.msg("删除成功");
                    startTree();
                    $("#rMenu").css({"visibility": "hidden"}); //设置右键菜单不可见
                    $("body").unbind("mousedown", onBodyMouseDown);
                    return true;
                }else{
                    layer.msg("删除失败");
                    return false;
                }
            }
        });
    }
}


//添加分类
function addHoverDom(){
    layer.prompt({
        formType: 2,
        value: '请输入添加分类',
        title: '添加分类',
        area: ['500px', '30px'] //自定义文本域宽高
    }, function(value, index, elem){
        $.ajax({
            url:'/Product/addProductCaegory',
            dataType:'json',
            data:{
                "parentId":node.categroyId,"sort":null,"title":value,
                "categroy":1,"createId":user.userId
            },
            success:function (data) {
                if(data.data){
                    layer.msg("添加成功");
                    startTree();
                }else{
                    layer.msg("添加失败");
                }
            }
        });
        layer.close(index);
    });
}
//修改分类
function Rename() {
    layer.prompt({
        formType: 2,
        value: '请输入修改分类名',
        title: '修改分类名',
        area: ['500px', '30px'] //自定义文本域宽高
    }, function(value, index, elem){
        if(value.length < 3){
            alert("名称不能少于3个字符！");
        }else{
            $.ajax({
                url:'/Product/updateProductCaegory',
                data:{"categoryId":node.categroyId,"title":value},
                dataType:'json',
                success:function (data) {
                    if(data.data){
                        layer.msg("修改成功");
                        startTree();
                        startTab();
                        return true;
                    }else{
                        layer.msg("修改失败");
                        return false;
                    }
                }
            });
            layer.close(index);
        }
    });
}


//刷新
function refresh() {
    window.location.reload();
}

//搜索
function selProduct() {
    var productName = $('input[name = title]').val();
    var productSate = $("select[name=productSate]").val();
    var productLabel = $('input[name = productLabel]').val();
    var product = {
        categoryId :productType,
        productName:productName,
        productSate:productSate,
        productLabel:productLabel
    }
    $.ajax({
        url:'/Product/queryProduct',
        dataType:'json',
        data:product,
        success:function (data) {
            tab(data.data);
        }
    });
}
//重置
function reset(){
    $('input[name = title]').val("");
    $("select[name=proTitle]").val('0');
}

//高级搜索
function accurate() {
    layer.open({
        type:2,
        content:"/Manageproductlist/productlist-precisesearch.html",
        area:['490px','500px'],
        end:function () {

        }
    })
}

//商品分类
$.ajax({
    url:'/Product/productCategroys',
    dataType:'json',
    success:function (data) {
        $.each(data.data, function (index, item) {
            $('#proTitle').append(new Option(item.title, item.categroyId));// 下拉菜单里添加元素
        });
        layui.form.render("select");
    }
});
//查看详情
function details(id){
    $('#proId').val(id);
    layer.open({
        type:2,
        content:"/Manageproductlist/Detailsoftheauditofgoods.html",
        area:['1020px','500px'],
        end:function () {

        }
    })
}

//编辑
function edit(id){
    $('#proId').val(id);
    layer.open({
        type:2,
        content:"/Manageproductlist/productlist-modify.html",
        area:['670px','500px'],
        end:function () {
            startTab();
        }
    })
}
//添加商品
function addProduct() {
    location.href="addProduct.html";
}
//删除商品
function delProduct(id,code) {
    //添加查询的操作日志
    $.ajax({
        url:'/Product/addProductOperationRecord',
        dataType:'json',
        data:{
            "logType":1,"type":3,"userId":user.userId,
            "remark":"删除反馈日志"
        }
    });
    layer.open({
        type:1,
        content:"<div style='font-size: 20px ; color: red; margin:30px  ;'>是否删除此商品?</div>",
        area:['300px','200px'],
        btn:["确定","取消"],
        yes: function (index,layero) {
            $.ajax({
                url:'/Product/delProduct',
                dataType:'json',
                data:{"productId":id},
                success:function (data) {
                    if(data){
                        layer.msg("删除成功");
                        startTab();
                    }else{
                        layer.msg("删除失败");
                    }
                    layer.close(index);
                }
            });
        },
        btn2: function (index,layero) {
            layer.close(index);
        }
    });
}
//日志
function commodityLog(id) {
    $('#proId').val(id);
    layer.open({
        type:2,
        content:"/Manageproductlist/productJournal.html",
        area:['995px','83%'],
        success:function (layero, index) {
            layero.find('iframe')[0].contentWindow.dis();
        }
    });
}
//审核详情
function auditDetails(id) {
    $('#proId').val(id);
    layer.open({
        type:2,
        content:"/Manageproductlist/product-auditDetails.html",
        area:['1020px','500px'],
    });
}
//导入
function daoRu() {
    layer.open({
        type: 1,
        title: "拖拽上传",
        content: $("#test10"),
        shade: 0.5,
        offset: 'auto',
        success: function (layero,index) {
            upload.render({
                elem: "#test10",
                url: "/Product/importExcel",
                method: "post",
                field: "file",
                accept: "file",
                drag: true,
                multiple: false,
                exts:'xlsx|xls',
                done: function (res, index, upload) {
                    if (res.data) {
                        layer.msg("导入成功");
                        location.reload();
                    } else {
                        layer.msg("导入失败");
                    }
                }
            });
        }
    });
}

function backOff() {
    var arr = localStorage.getItem("numArr");
    var numArr = arr.split(",");
    numArr.pop();
    window.parent.layui.element.tabChange('tab',numArr[numArr.length - 1]);
    localStorage.setItem("numArr",numArr);
}
